<template>
  <view class="profile-container">
    <up-navbar title="个人信息" :leftIcon="''" />
    <view style="height: 44px;"></view>

    <!-- 用户名 -->
    <view class="username-section">
      <text class="username">用户姓名:{{ studentName }}</text>
    </view>
    <view class="tab-container">
      <text
          :class="['tab-item', { active: currentTab === 'activities' }]"
          @tap="currentTab = 'activities'"
      >参加的活动</text>
      <text
          :class="['tab-item', { active: currentTab === 'records' }]"
          @tap="currentTab = 'records'"
      >我的兑换记录</text>
    </view>


    <!-- 积分展示 -->
    <view class="info-card">
      <view class="info-item">
        <up-icon name="star-fill" color="#ff9800" size="24" />
        <text class="info-text">积分：{{ point }}</text>
      </view>
    </view>

    <view v-if="currentTab === 'activities'" class="section">
      <!-- 活动记录 -->
      <view v-if="activities.length > 0">
        <view v-for="(act, index) in activities" :key="index" class="activity-card">
          <text class="activity-name">{{ act.activityName }}</text>
          <text class="activity-time">时间：{{ act.activityTime }}</text>
          <text class="activity-status"
                :class="{ signed: act.status === 2 }">
            {{ act.status === 2 ? '✅ 已签到' : '❌ 未签到' }}
          </text>
          <!-- 取消报名按钮 -->
          <view
              v-if="!isActivityExpired(act.endTime) && act.status !== 2"
              class="btn-cancel"
              @tap="() => handleDelete(act.id)"
          >
            取消报名
          </view>
        </view>
      </view>
    <view v-else class="no-data">暂无活动记录</view>
  </view>

    <view v-if="currentTab === 'records'" class="section">
      <!-- 兑换记录 -->
      <view v-if="records.length === 0" class="no-data">暂无兑换记录</view>
      <view v-for="record in records" :key="record.id" class="activity-card">
        <view class="activity-name">{{ record.giftName }}</view>
        <view class="activity-time">时间：{{ formatTime(record.createTime) }}</view>
        <view class="activity-point">积分：{{ record.point }}</view>
        <view class="activity-status">{{ record.status }}</view>
        <!-- 收货人信息 -->
        <view class="receiver-info" v-if="record.receiveName">
          <text>收货人：{{ record.receiveName }} | {{ record.receivePhone }}</text><br/>
          <text>地址：{{ record.address }}</text>
        </view>
      </view>
    </view>
    <!-- 退出登录按钮 -->
    <view class="logout-button" @tap="logout">
      <text>退出登录</text>
    </view>
  </view>
</template>

<script setup>
const currentTab = ref('activities') // 默认显示活动记录
import { format } from 'date-fns'

// 格式化日期时间
const formatTime = (time) => {
  if (!time) return ''
  try {
    return format(new Date(time), 'yyyy-MM-dd HH:mm:ss')
  } catch (e) {
    return time
  }
}

import { ref, onMounted } from 'vue'
import { getStudentTotalPoint,
          getStudentActivities,

          deleteActivityHistoryById} from '@/http/student'

const studentName = ref('')
const point = ref(0)
const activities = ref([])

const fetchProfile = async () => {
  const studentId = uni.getStorageSync('studentId')
  if (!studentId) {
    uni.showToast({ title: '未登录' })
    return
  }

  try {
    // 获取学生姓名 + 积分
    const infoRes = await getStudentTotalPoint(studentId)


    console.log('接口返回:', infoRes)

    const data = infoRes?.data || {}

    // const data = infoRes.data
    studentName.value = infoRes.studentName || '未知用户'
    point.value = infoRes.point || 0

    // 获取活动记录
    const activityRes = await getStudentActivities(studentId)
    console.log('活动数据:', activityRes)

    activities.value = activityRes|| []
  } catch (error) {
    uni.showToast({ title: '加载失败', icon: 'none' })
    console.error('Failed to load profile:', error)
  }
}

import { getExchangeRecords } from '../../http/gift'

const records = ref([])

onMounted(async () => {
  const studentId = uni.getStorageSync('studentId')
  const res = await getExchangeRecords(studentId)
  records.value = res
})
onMounted(() => {
  fetchProfile()
})

const logout = () => {
  // 清除本地缓存的用户信息
  uni.removeStorageSync('studentId')
  uni.removeStorageSync('studentName')
  uni.removeStorageSync('accessToken')
  uni.removeStorageSync('tokenType')

  // 跳转到登录页面（请根据实际路径修改）
  uni.reLaunch({
    url: '/pages/login/login'
  })
}

// 判断活动是否已过期
const isActivityExpired = (endTime) => {
  if (!endTime) return false;
  return new Date(endTime.replace(/-/g, '/')).getTime() < Date.now();
};

// 在 profile.vue 或 activity.vue 中
const handleDelete = async (historyId) => {
  uni.showModal({
    title: '提示',
    content: '确定要取消参加这活动吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await deleteActivityHistoryById(historyId)
          uni.showToast({ title: '取消成功', icon: 'success' })
          // 刷新页面数据
          fetchProfile()
        } catch (err) {
          uni.showToast({ title: '取消失败', icon: 'none' })
          console.error('取消参加失败:', err)
        }
      }
    }
  })
}
const refreshActivities = async () => {
  const historyList = await getStudentActivities(studentId)
  const joinedMap = historyList.reduce((acc, h) => {
    acc[h.activityId] = h
    return acc
  }, {})

  const updatedList = activityList.value.map(item => {
    const history = joinedMap[item.id] || {}
    return {
      ...item,
      joined: history.status === 1 || history.status === 2,
      checkedIn: history.status === 2,
      canceled: history.status === 3
    }
  })

  activityList.value = updatedList
}


</script>

<style scoped>
.btn-cancel {
  margin-top: 16rpx;
  padding: 12rpx 24rpx;
  background-color: #ff4d4f;
  color: white;
  font-size: 24rpx;
  border-radius: 32rpx;
  display: inline-block;
  text-align: center;
}
.btn-cancel:active {
  background-color: #e63c3c;
}

.tab-container {
  display: flex;
  justify-content: space-around;
  padding: 20rpx 0;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.tab-item {
  font-size: 28rpx;
  color: #666;
  padding: 16rpx 32rpx;
  border-radius: 32rpx;
  transition: all 0.3s ease;
}

.tab-item.active {
  color: #1890ff;
  background-color: #e8f4ff;
}


.logout-button {
  margin: 40rpx 24rpx 0;
  padding: 24rpx;
  background-color: #ff4d4f;
  color: #fff;
  text-align: center;
  font-size: 28rpx;
  border-radius: 32rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 77, 79, 0.2);
}

.logout-button:active {
  background-color: #e63c3c;
}


.profile-container {
  padding: 24rpx;
  background-color: #f7f9fa;
}

.username {
  font-size: 36rpx;
  font-weight: bold;
  color: #222;
}
.username-section {
  padding: 32rpx 24rpx;
  text-align: center;
}
/* 信息卡片 */
.info-card {
  padding: 32rpx 40rpx;
  background-color: #ffffff;
  margin: 20rpx 24rpx 0;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
}
.info-item {
  display: flex;
  align-items: center;
  justify-content: center;
}
.info-text {
  margin-left: 16rpx;
  font-size: 28rpx;
  color: #333;
}
/* 活动区域 */
.section {
  margin: 32rpx 24rpx;
}
.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 24rpx;
  display: block;
}

/* 活动卡片 */
.activity-card {
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  position: relative;
}
.activity-name {
  font-size: 30rpx;
  font-weight: bold;
  margin-bottom: 12rpx;
  display: block;
}
.activity-time,
.activity-point {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 8rpx;
}
.activity-status {
  font-size: 26rpx;
  color: #ff4d4f;
  font-weight: bold;
}
.activity-status.signed {
  color: #4caf50;
}
.no-data {
  text-align: center;
  color: #aaa;
  margin-top: 60rpx;
}

.profile-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
  margin-bottom: 40rpx;
}

.profile-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.label {
  font-weight: bold;
  color: #333;
  width: 120rpx;
}

.value {
  color: #666;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  display: block;
}

.activity-item {
  background: #f0f0f0;
  padding: 20rpx;
  border-radius: 16rpx;
  margin-bottom: 16rpx;
}

.receiver-info {
  margin-top: 12rpx;
  font-size: 24rpx;
  color: #555;
  line-height: 1.5;
}
</style>
